package com.ymatou.apigateway.testcase;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.shop2cn.iapi.shenqisettlement.parameter.bean.AgentProductBean;
import com.shop2cn.iapi.sqoptrade.resp.TradingServiceResp;
import com.ymatou.apigateway.parameter.AesUtil;
import com.ymatou.apigateway.parameter.OpenapiReq;
import com.ymatou.apigateway.parameter.SqMultiSegmentsDeliverReq;
import com.ymatou.apigateway.parameter.pojo.DeliveryPackage;
import com.ymatou.apigateway.parameter.pojo.LogisticsSegment;
import com.ymatou.apigateway.service.OpenapiService;
import com.ymatou.apigateway.service.SqMultiSegmentsDeliverCall;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.SQPayGateWayCallService;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.shenqi.DGSQBuildProxyChainCallService;
import com.ymttest.business.service.shenqi.SqTradingCallService;
import com.ymttest.database.model.Application;
import com.ymttest.database.model.AuthCode;
import com.ymttest.database.sqlwapper.OpenApiWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class Ts_SqMultiSegmentsDeliver {

	private static OpenapiReq openapiReq;
	private static OpenApiWapper openApiWapper;
	
	private static SqMultiSegmentsDeliverReq sqMultiSegmentsDeliverReq;
	private static SqMultiSegmentsDeliverCall sqMultiSegmentsDeliverCall;
	
	private static long autotest_goodsOwnerId = Long.valueOf(EnvSetup
			.getData("autotest_goodsOwnerId")); 

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("openapi神器多段发货");
		openApiWapper = new OpenApiWapper();
	}

	@Before
	public void caseUp() {

		openapiReq = new OpenapiReq();
		
		sqMultiSegmentsDeliverReq = new SqMultiSegmentsDeliverReq();
		sqMultiSegmentsDeliverCall = new SqMultiSegmentsDeliverCall();
		
		openapiReq.setMethod("sq.order.multisegments.deliver");
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(sqMultiSegmentsDeliverCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SqMultiSegmentsDeliver_001() {
		Logger.start(true, "openapi神器多段发货，一个包裹一个段");
		try {
			
			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false,
							false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder(productBean);

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			Long userId = placeOrderResp.getUserId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(),
					productBean.getCurrency());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(5000);

			// 接单
			TradingCallService
					.sellerAcceptOrder(autotest_goodsOwnerId, orderId);
			TradingSyncService.getSyncResult(orderId);
			
			LogisticsSegment logisticsSegment = new LogisticsSegment();
			
			logisticsSegment.setLogistics_company_id("Y103");
			logisticsSegment.setLogistics_company_name("SF");
			logisticsSegment.setTracking_number(TestDataManager.randomStr(8));
			
			DeliveryPackage deliveryPackage = new DeliveryPackage();
			
			deliveryPackage.setLogistics_segments(Arrays.asList(logisticsSegment));
			
			sqMultiSegmentsDeliverReq.setOrder_id(orderId);
			sqMultiSegmentsDeliverReq.setPackages(Arrays.asList(deliveryPackage));

			Application application = openApiWapper
					.selectApplicationBySellerId(productBean.getSellerId()).get(0);

			String app_id = application.getApp_id();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);

			String app_secret = application.getApp_secret();

			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(sqMultiSegmentsDeliverReq));
			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.order.multisegments.deliver",
							app_id);

			sqMultiSegmentsDeliverCall.setUrl(url);

			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			sqMultiSegmentsDeliverCall.setData(openapiReq);

			sqMultiSegmentsDeliverCall.callService();

			Logger.verifyEquals("0000", sqMultiSegmentsDeliverCall.getCode(), 
					"校验code");
			Logger.verifyEquals("", sqMultiSegmentsDeliverCall.getMessage(),
					"校验message");

			Logger.verifyNotNull(sqMultiSegmentsDeliverCall.getContent(),
					"校验content");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SqMultiSegmentsDeliver_002() {
		Logger.start(true, "openapi神器多段发货，一个包裹多个段");
		try {
			
			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false,
							false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder(productBean);

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			Long userId = placeOrderResp.getUserId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(),
					productBean.getCurrency());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(5000);

			// 接单
			TradingCallService
					.sellerAcceptOrder(autotest_goodsOwnerId, orderId);
			TradingSyncService.getSyncResult(orderId);
			
			List<LogisticsSegment> logisticsSegmentList = new ArrayList<>();
			
			for (int i = 0; i < 2; i++) {
				
				LogisticsSegment logisticsSegment = new LogisticsSegment();
				
				logisticsSegment.setLogistics_company_id("Y103");
				logisticsSegment.setLogistics_company_name("SF");
				logisticsSegment.setTracking_number(TestDataManager.randomStr(8));
				
				logisticsSegmentList.add(logisticsSegment);
			}
			
			DeliveryPackage deliveryPackage = new DeliveryPackage();
			
			deliveryPackage.setLogistics_segments(logisticsSegmentList);
			
			sqMultiSegmentsDeliverReq.setOrder_id(orderId);
			sqMultiSegmentsDeliverReq.setPackages(Arrays.asList(deliveryPackage));

			Application application = openApiWapper
					.selectApplicationBySellerId(productBean.getSellerId()).get(0);

			String app_id = application.getApp_id();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);

			String app_secret = application.getApp_secret();

			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(sqMultiSegmentsDeliverReq));
			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.order.multisegments.deliver",
							app_id);

			sqMultiSegmentsDeliverCall.setUrl(url);

			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			sqMultiSegmentsDeliverCall.setData(openapiReq);

			sqMultiSegmentsDeliverCall.callService();

			Logger.verifyEquals("0000", sqMultiSegmentsDeliverCall.getCode(), 
					"校验code");
			Logger.verifyEquals("", sqMultiSegmentsDeliverCall.getMessage(),
					"校验message");

			Logger.verifyNotNull(sqMultiSegmentsDeliverCall.getContent(),
					"校验content");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SqMultiSegmentsDeliver_003() {
		Logger.start(true, "openapi神器多段发货，多个包裹多个段");
		try {
			
			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false,
							false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder(productBean);

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			Long userId = placeOrderResp.getUserId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(),
					productBean.getCurrency());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(5000);

			// 接单
			TradingCallService
					.sellerAcceptOrder(autotest_goodsOwnerId, orderId);
			TradingSyncService.getSyncResult(orderId);
			
			List<DeliveryPackage> deliveryPackageList = new ArrayList<>();
			
			for (int i = 0; i < 2; i++) {
				
				List<LogisticsSegment> logisticsSegmentList = new ArrayList<>();
				
				for (int j = 0; j < 2; j++) {
					
					LogisticsSegment logisticsSegment = new LogisticsSegment();
					
					logisticsSegment.setLogistics_company_id("Y103");
					logisticsSegment.setLogistics_company_name("SF");
					logisticsSegment.setTracking_number(TestDataManager.randomStr(8));
					
					logisticsSegmentList.add(logisticsSegment);
				}
				
				DeliveryPackage deliveryPackage = new DeliveryPackage();
				
				deliveryPackage.setLogistics_segments(logisticsSegmentList);
				
				deliveryPackageList.add(deliveryPackage);
			}
			
			sqMultiSegmentsDeliverReq.setOrder_id(orderId);
			sqMultiSegmentsDeliverReq.setPackages(deliveryPackageList);

			Application application = openApiWapper
					.selectApplicationBySellerId(productBean.getSellerId()).get(0);

			String app_id = application.getApp_id();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);

			String app_secret = application.getApp_secret();

			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(sqMultiSegmentsDeliverReq));
			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.order.multisegments.deliver",
							app_id);

			sqMultiSegmentsDeliverCall.setUrl(url);

			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			sqMultiSegmentsDeliverCall.setData(openapiReq);

			sqMultiSegmentsDeliverCall.callService();

			Logger.verifyEquals("0000", sqMultiSegmentsDeliverCall.getCode(), 
					"校验code");
			Logger.verifyEquals("", sqMultiSegmentsDeliverCall.getMessage(),
					"校验message");

			Logger.verifyNotNull(sqMultiSegmentsDeliverCall.getContent(),
					"校验content");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_SqMultiSegmentsDeliver_004() {
		Logger.start(true, "openapi神器多段发货，多个包裹多个段，重复发货");
		try {
			
			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 0, false,
							false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrder(productBean);

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			Long userId = placeOrderResp.getUserId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId());

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(),
					productBean.getCurrency());

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(5000);

			// 接单
			TradingCallService
					.sellerAcceptOrder(autotest_goodsOwnerId, orderId);
			TradingSyncService.getSyncResult(orderId);
			
			for (int k = 0; k < 2; k++) {
				
				List<DeliveryPackage> deliveryPackageList = new ArrayList<>();
				
				for (int i = 0; i < 2; i++) {
					
					List<LogisticsSegment> logisticsSegmentList = new ArrayList<>();
					
					for (int j = 0; j < 2; j++) {
						
						LogisticsSegment logisticsSegment = new LogisticsSegment();
						
						logisticsSegment.setLogistics_company_id("Y103");
						logisticsSegment.setLogistics_company_name("SF");
						logisticsSegment.setTracking_number(TestDataManager.randomStr(8));
						
						logisticsSegmentList.add(logisticsSegment);
					}
					
					DeliveryPackage deliveryPackage = new DeliveryPackage();
					
					deliveryPackage.setLogistics_segments(logisticsSegmentList);
					
					deliveryPackageList.add(deliveryPackage);
				}
				
				sqMultiSegmentsDeliverReq.setOrder_id(orderId);
				sqMultiSegmentsDeliverReq.setPackages(deliveryPackageList);

				Application application = openApiWapper
						.selectApplicationBySellerId(productBean.getSellerId()).get(0);

				String app_id = application.getApp_id();

				AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
						.get(0);

				openapiReq.setApp_id(app_id);

				String app_secret = application.getApp_secret();

				openapiReq.setSign_method("MD5");
				openapiReq.setAuth_code(authCode.getAuth_code());
				openapiReq.setTimestamp(YMTDateUtil.getSysTime());
				openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
				openapiReq.setBiz_content(new FormatUtil()
						.beanToGSONString(sqMultiSegmentsDeliverReq));
				String url = String
						.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.order.multisegments.deliver",
								app_id);

				sqMultiSegmentsDeliverCall.setUrl(url);

				openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
						AesUtil.decrypt(app_secret)));

				sqMultiSegmentsDeliverCall.setData(openapiReq);

				sqMultiSegmentsDeliverCall.callService();

				Logger.verifyEquals("0000", sqMultiSegmentsDeliverCall.getCode(), 
						"校验code");
				Logger.verifyEquals("", sqMultiSegmentsDeliverCall.getMessage(),
						"校验message");

				Logger.verifyNotNull(sqMultiSegmentsDeliverCall.getContent(),
						"校验content");
				
				Thread.sleep(10000);
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	public static void main(String[] args) {
		
//		Ts_SqGetRefundBillDetail test = new Ts_SqGetRefundBillDetail();
	}
}
